package edu.auctionmart.jobs

import org.quartz.Job
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import edu.auctionmart.Auction
import edu.auctionmart.EmailService;
import edu.auctionmart.IvrService;
import edu.auctionmart.QueueService
import edu.auctionmart.SmsService;
import edu.auctionmart.User


class AlertReminderJob implements Job {

	JobExecutionContext context


	public String runJob() {
		context.getJobDetail().getFullName()
		println("Job executed and fired: " + context.getTrigger().getFullJobName())

		String[] jobInfo = context.getTrigger().getJobName().split("[.]")

		String auctionName = jobInfo[1]
		String userName = jobInfo[2]
		String alertType = jobInfo[3]

		Auction theAuction = Auction.findByAuctionTitle(auctionName)
		User user = User.findByUsername(userName)

		if (theAuction == null || user == null) {
			//Auction may have been deleted for some reason, or user, so no alerts will be sent
			println("Auction or user didn't exist")
			return "Finished"
		}

		println(theAuction.getAuctionTitle())
		println(user.getUsername())

		if (jobInfo.length == 4) {
			if (alertType.equals("SMS")) {
				if (user?.profile?.contactPhoneNumber) {
					println("Placing SMS")
					SmsService smsService = (SmsService) context.getJobDetail().getJobDataMap().get("service")
					smsService.sendSMS(user.profile.contactPhoneNumber, theAuction, user)
				} else {
					println("Could not place SMS")
				}
			} else if (alertType.equals("IVR")) {
				if (user?.profile?.contactPhoneNumber) {
					println("Placing call")
					IvrService ivrService = (IvrService) context.getJobDetail().getJobDataMap().get("service")
					ivrService.placeCall(user.profile.contactPhoneNumber, theAuction, user)
				} else {
					println("Could not place call")
				}
			} else if (alertType.equals("EMAIL")) {
				EmailService emailService = (EmailService) context.getJobDetail().getJobDataMap().get("service")
				emailService.sendEmail(user, theAuction)
			}
			return "Finished"
		}
		else { //Should never occur, but if it does, do not try to execute anything
			return "Finished"
		}

	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		this.context = context
		QueueService queueService = (QueueService) context.getJobDetail().getJobDataMap().get("queueService")
		queueService.addToQueueAndExecute(this)
	}
}
